import json
import pymssql
# from fastapi import FastAPI, Query
import configparser

from models import Customer

def get_all_customers():
    config = load_config()
    customers_list = list[Customer]
    # DATABASE_URL = f"mssql+pymssql://{config['username']}:{config['password']}@{config['host']}:{config['port']}/{config['database']}"
    # conn = pymssql.connect(host=DATABASE_URL.split("//")[1].split("/")[0],
    #                        user=DATABASE_URL.split("//")[1].split("@")[0].split("/")[0],
    #                        password=DATABASE_URL.split("//")[1].split("@")[0].split("/")[1],
    #                        database=DATABASE_URL.split("//")[1].split("@")[1].split("/")[1],
    #                        port=int(DATABASE_URL.split("//")[1].split("@")[1].split("/")[0]))
    conn = pymssql.connect(server=config['host'], user=config['username'], password=config['password'], database=config['database'], tds_version="7.0", charset='cp1251')
    cursor = conn.cursor(as_dict=True)
    cursor.execute("SELECT top 10 ID as id, DESCR as name FROM SC2")
    customers = cursor.fetchall()
    for row in cursor:
        customers_list.append(Customer(v7id=row['id'], v7name=row['name']))
        print("ID=%s, NAME=%s" % (row['id'], row['name']))
    cursor.close()
    conn.close()
    print(type(customers))
    return customers_list

# async def get_customers_by_page(page: int = Query(..., ge=1)):
#     config = load_config()
#     DATABASE_URL = f"mssql+pymssql://{config['username']}:{config['password']}@{config['host']}:{config['port']}/{config['database']}"
#     conn = pymssql.connect(host=DATABASE_URL.split("//")[1].split("/")[0],
#                            user=DATABASE_URL.split("//")[1].split("@")[0].split("/")[0],
#                            password=DATABASE_URL.split("//")[1].split("@")[0].split("/")[1],
#                            database=DATABASE_URL.split("//")[1].split("@")[1].split("/")[1],
#                            port=int(DATABASE_URL.split("//")[1].split("@")[1].split("/")[0]))
#     cursor = conn.cursor()
#     offset = (page - 1) * 10
#     await cursor.execute(f"SELECT * FROM Customers OFFSET {offset} ROWS FETCH NEXT 10 ROWS ONLY")
#     customers = [row[0] for row in await cursor.fetchall()]
#     cursor.close()
#     conn.close()
#     return customers

def load_config():
    config = configparser.ConfigParser()
    config.read('config.ini')
    return config['database']


print(get_all_customers())